'use strict'
const path = require('path')

function resolve(dir) {
	return path.join(__dirname, dir)
}

const name = '数据大屏vue-yjr' // 页面标题

const port = process.env.port || process.env.npm_config_port || 9529 //开发环境端口号

const CWP = require('compression-webpack-plugin')
const CWPrules = ['js', 'css']

module.exports = {
	css: {
		loaderOptions: {
			// 配置全局sass
			sass: {
				prependData: `@import "@/styles/global.scss";`
			}
		}
	},
	publicPath: './',
	outputDir: 'dist',
	assetsDir: 'static',
	lintOnSave: false, //process.env.NODE_ENV === 'development',
	productionSourceMap: false,
	devServer: {
		hot: true,
		port: port,
		open: true,
		overlay: {
			warnings: false,
			errors: true
		}
	},
	configureWebpack: {
		externals: {
			'echarts': 'echarts', // cdn使用,避免打包  版本5.2.0  echarts
			'AMap': 'AMap', //cdn 避免打包  高德地图 版本1.4 1.5			
		},
		//在webpack的name字段中提供应用的标题，以便它可以在index.html中访问，以注入正确的标题。
		name: name,
		resolve: {
			alias: {
				'@': resolve('src')
			}
		},
		plugins: [
			/*
			Gzip打包优化配置
			配置compression-webpack-plugin压缩  记得版本降低到6.1.1  		
			
			new CWP({
				filename: "[path].gz[query]", //目标资源名称
				algorithm: 'gzip',
				test: new RegExp('\\.(' + CWPrules.join('|') + ')$'),
				threshold: 10240,
				minRatio: 0.8
			})
			*/
		]
	},

	chainWebpack(config) {

		//可以提高首屏加载的速度，建议开启预加载
		config.plugin('preload').tap(() => [{
			rel: 'preload',
			fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
			include: 'initial'
		}])

		//cur文件支持
		config.module
			.rule('url-loader')
			.test(/\.(cur)(\?.*)?$/)
			.use('url-loader')
			.loader('url-loader')
			.end()

		//当页面太多时，会导致太多无意义的请求
		config.plugins.delete('prefetch')

		config.when(process.env.NODE_ENV !== 'development',
			config => {
				config.plugin('ScriptExtHtmlWebpackPlugin').after('html').use('script-ext-html-webpack-plugin', [{
					// 'runtime' 必须与runtimeChunk名称相同。 默认是 'runtime'
					inline: /runtime\..*\.js$/
				}]).end()

				config.optimization.splitChunks({
					chunks: 'all',
					cacheGroups: {
						libs: {
							name: 'chunk-libs',
							test: /[\\/]node_modules[\\/]/,
							priority: 10,
							chunks: 'initial' //只打包最初依赖的第三方
						},
						commons: {
							name: 'chunk-commons',
							test: resolve('src/components'), // 自定义规则
							minChunks: 3, //常用的基本上就是3个
							priority: 5,
							reuseExistingChunk: true
						}
					}
				})
				config.optimization.runtimeChunk('single')
			}
		)
	}
}
